<?php


namespace App\Http\Services;


class PlatformDependentChars
{
    static public function check($str, $input_encoding = false, $to_encoding = 'sjis-win') {
        if (empty($str) || !is_string($str)) {
            return true;
        }
        if (! $input_encoding) {
            $input_encoding = mb_internal_encoding();
        }
        if (self::isSjis($input_encoding)) {
            $to_encoding   = 'utf-8';
        }
        $convertedStr = self::reconvert($str, $input_encoding, $to_encoding);
        if ($str === $convertedStr) {
            return true;
        }
        $diff_char = '';
        for($i = 0; $i < mb_strlen($str, 'utf-8'); $i++) {
            $u8 = mb_substr($str, $i, 1, 'utf-8');
            $sjis = mb_substr($convertedStr, $i, 1, 'utf-8');
            if ($u8 !== $sjis) {
                $diff_char = $u8;
                break;
            }
        }
        return $diff_char;
    }

    static public function isSjis($encoding = false) {
        $sjisNames = self::getSjisAliases();
        $sjisNames[] = 'sjis-win';
        return self::arrayKeyExistsCaseInsensitive($encoding, $sjisNames);
    }

    static public function getSjisAliases() {
        $aliases = mb_encoding_aliases('SJIS');
        if ($mimeName = mb_preferred_mime_name('sjis-win')) {
            $aliases[] = $mimeName;
        }
        return $aliases;
    }

    static public function arrayKeyExistsCaseInsensitive($key, $search) {
        return array_key_exists(strtolower($key), array_change_key_case($search));
    }

    static public function reconvert($str, $input_encoding, $to_encoding) {
        $convertedStr = mb_convert_encoding($str,          $to_encoding,   $input_encoding);
        $convertedStr = mb_convert_encoding($convertedStr, $input_encoding, $to_encoding);
        return $convertedStr;
    }
}
